<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--左侧树-->
      <!-- 资源库类型 1-公共资料库 2-行业资料库 3-企业资料库 -->
      <el-col v-if="theType === 1 || theType === 3" :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="treeName"
            placeholder="请输入分类名称"
            clearable
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="treeOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            @node-click="handleNodeClick"
            :highlight-current="true"
            node-key="id"
            :default-expanded-keys="defaultExpandkeys"
            accordion
            class="tree-container"
          />
        </div>
      </el-col>
      <el-col v-if="theType === 2" :span="4" :xs="24">
        <div class="head-container">
          <el-select
            v-model="industryParams.industryId"
            style="margin-bottom: 20px"
            placeholder="请选择"
            @change="changeIndustry"
          >
            <el-option
              v-for="item in industryOptions"
              :key="item.id"
              :label="item.label"
              :value="item.id"
            ></el-option>
          </el-select>
        </div>
        <div class="head-container">
          <el-tree
            :data="classOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            ref="tree"
            @node-click="handleNodeClick"
            :highlight-current="true"
            node-key="id"
            :default-expanded-keys="defaultExpandkeys"
            accordion
            class="tree-container"
          />
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="20" :xs="24">
        <el-form
          :model="queryParams"
          ref="queryForm"
          v-show="showSearch"
          :inline="true"
          label-width="80px"
        >
          <!-- <el-form-item label="资料库" prop="status">
                <el-select
                v-model="queryParams.status"
                placeholder="资料库"
                clearable
                size="small"
                style="width: 240px"
                >
                <el-option
                    v-for="dict in statusOptions"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="dict.dictValue"
                />
                </el-select>
            </el-form-item> -->
          <el-form-item label="文章类型" prop="visitType">
            <el-select
              v-model="queryParams.visitType"
              placeholder="文章类型"
              clearable
              size="small"
              style="width: 240px"
            >
              <el-option
                v-for="item in visitTypeOptions"
                :key="item.id"
                :label="item.label"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="关键字" prop="keywords">
            <el-input
              v-model="queryParams.keywords"
              placeholder="请输入文章名称"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
              size="small"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
              >重置</el-button
            >
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              v-if="theType == 1"
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              v-hasPermi="['91110']"
              @click="handleAdd"
              >添加文章</el-button
            >
            <el-button
              v-if="theType == 2"
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              v-hasPermi="['91210']"
              @click="handleAdd"
              >添加文章</el-button
            >
            <el-button
              v-if="theType == 3"
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              v-hasPermi="['91310']"
              @click="handleAdd"
              >添加文章</el-button
            >
          </el-col>
          <right-toolbar
            :showSearch.sync="showSearch"
            @queryTable="getList"
          ></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="tableList" :border="true">
          <el-table-column
            v-if="theType == 1"
            label="公共栏目分类"
            align="center"
            prop="publicClassification"
            width="100"
          />
          <el-table-column
            v-if="theType == 2"
            label="公共栏目分类"
            align="center"
            prop="industryClassification"
            width="100"
          />
          <el-table-column
            v-if="theType == 3"
            label="公共栏目分类"
            align="center"
            prop="enterpriseClassification"
            width="120"
          />
          <el-table-column
            label="文章标题"
            align="center"
            prop="label"
            :show-overflow-tooltip="true"
            width="180"
          />
          <el-table-column align="center" prop="thumb" label="配图" width="80">
            <template slot-scope="scope">
              <imagePreview :src="scope.row.thumb" />
            </template>
          </el-table-column>
          <el-table-column label="文章类型" align="center" prop="theType">
            <template slot-scope="scope">
              <span>{{ findVisitType(scope.row.theType) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="文章内容"
            align="center"
            prop="content"
            :show-overflow-tooltip="true"
            width="260"
          >
            <template slot-scope="scope">
              <span v-html="scope.row.content"></span>
            </template>
          </el-table-column>
          <el-table-column label="阅读数" align="center" prop="theUsage" />
          <el-table-column label="归档" align="center" key="enable">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.enable"
                :active-value="1"
                :inactive-value="0"
                @change="handlefileChange(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column
            label="添加时间"
            align="center"
            prop="releaseTime"
            width="120"
          />
          <el-table-column label="录入员" align="center" prop="publisher" />
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
            fixed="right"
            width="100"
          >
            <template slot-scope="scope">
              <div v-if="scope.row.enable === 0">
                <el-button
                  v-if="theType == 1"
                  size="mini"
                  type="text"
                  v-hasPermi="['91120']"
                  @click="handleUpdate(scope.row)"
                  >修改</el-button
                >
                <el-button
                  v-if="theType == 2"
                  size="mini"
                  type="text"
                  v-hasPermi="['91220']"
                  @click="handleUpdate(scope.row)"
                  >修改</el-button
                >
                <el-button
                  v-if="theType == 3"
                  size="mini"
                  type="text"
                  v-hasPermi="['91320']"
                  @click="handleUpdate(scope.row)"
                  >修改</el-button
                >

                <el-button
                  v-if="theType == 1"
                  size="mini"
                  type="text"
                  v-hasPermi="['91130']"
                  @click="handleDelete(scope.row)"
                  >删除</el-button
                >
                <el-button
                  v-if="theType == 2"
                  size="mini"
                  type="text"
                  v-hasPermi="['91230']"
                  @click="handleDelete(scope.row)"
                  >删除</el-button
                >
                <el-button
                  v-if="theType == 3"
                  size="mini"
                  type="text"
                  v-hasPermi="['91330']"
                  @click="handleDelete(scope.row)"
                  >删除</el-button
                >
              </div>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />

        <!-- 添加或修改参数配置对话框 -->
        <el-dialog
          :title="title"
          :visible.sync="open"
          width="600px"
          append-to-body
          class="component-upload"
        >
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <!-- *栏目(下拉框)、*文章标题、配图、*文章类型(下拉框)、*文章内容（富文本） -->
            <el-row>
              <el-col :span="12">
                <el-form-item label="栏目分类" prop="baseId">
                  <el-select
                    v-model="form.baseId"
                    placeholder="请选择"
                    @change="changeClass"
                  >
                    <el-option
                      v-for="item in classOptions"
                      :key="item.id"
                      :label="item.label"
                      :value="item.id"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="文章标题" prop="title">
                  <el-input v-model="form.title" placeholder="请输入文章标题" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="资源学时" prop="classHours">
                  <el-input-number
                    v-model="form.classHours"
                    :precision="0"
                    controls-position="right"
                    :min="0"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="资源学分" prop="credit">
                  <el-input-number
                    v-model="form.credit"
                    :precision="0"
                    controls-position="right"
                    :min="0"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <!-- 文章类型: 富文本、PPT、PDF、WORD; -->
              <el-col :span="12">
                <el-form-item label="文章类型" prop="theType">
                  <el-select v-model="form.theType" placeholder="请选择">
                    <el-option
                      v-for="item in visitTypeOptions"
                      :key="item.id"
                      :label="item.label"
                      :value="item.id"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="文章内容" prop="content">
              <editor v-model="form.content" :min-height="192" />
            </el-form-item>
            <el-form-item label="附件" prop="theLink">
              <fileUpload v-model="form.theLink" />
            </el-form-item>
            <el-form-item label="配图" prop="thumb">
              <uploadImage v-model="form.thumb" />
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-dialog>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import UploadImage from "@/components/ImageUpload";
import Editor from "@/components/Editor";
import FileUpload from "@/components/FileUpload";
import {
  getPage,
  listData,
  getData,
  delData,
  addData,
  updateData,
  delMultiData,
  getSelect,
  getEnable,
} from "@/api/dataBase/dataBase";
import { getDict, getArticleType } from "@/api/select";
import { getClassTree } from "@/api/system/industryClass";

export default {
  name: "myArticle",
  components: {
    Treeselect,
    UploadImage,
    Editor,
    FileUpload,
  },
  data() {
    return {
      treeName: undefined,
      treeOptions: [],
      currentId: null,
      defaultExpandkeys: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      queryParams: {
        currentPage: 1,
        pagesize: 10,
        theType: undefined,
        category: undefined,
        keywords: undefined,
        visitType: undefined,
        resourceType: 1,
      },
      showSearch: true,
      loading: true,
      tableList: [],
      ids: [],
      single: true,
      multiple: true,
      total: 0,
      title: "",
      open: false,
      form: {
        baseId: undefined,
        articleTitle: undefined,
        thumb: undefined,
        atypeId: undefined,
        articleContent: undefined,
      },
      rules: {
        baseId: [
          { required: true, message: "栏目分类不能为空", trigger: "change" },
        ],
        title: [
          { required: true, message: "文章标题不能为空", trigger: "blur" },
        ],
        theType: [
          { required: true, message: "请选择文章类型", trigger: "change" },
        ],
        content: [
          { required: true, message: "文章内容不能为空", trigger: "blur" },
        ],
        classHours: [
          { required: true, message: "资源学时不能为空", trigger: "blur" },
          { pattern: /^\d+$/, message: "请输入整数", trigger: "blur" },
        ],
        credit: [
          { required: true, message: "资源学分不能为空", trigger: "blur" },
          { pattern: /^\d+$/, message: "请输入整数", trigger: "blur" },
        ],
        thumb: [
          { required: true, message: "配图不能为空", trigger: "blur" },
        ],
      },
      visitTypeOptions: [], //视频类型下拉框
      classOptions: [], //栏目分类下拉框
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        // headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        // url: process.env.VUE_APP_BASE_API + "/system/user/importData",
        url: "",
      },
      //所属行业对应行业资源分类
      industryParams: {
        industryId: undefined,
        industry: undefined,
        topLevel: 0,
      },
      industryOptions: [], //所属行业下拉框
    };
  },
  props: {
    theType: {
      type: Number,
      default: "",
    },
  },
  watch: {
    // 根据名称筛选部门树
    treeName(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    this.queryParams.theType = this.theType;
    if (this.theType != 2) this.getPageInfo();
    this.getSelect();
    // 文章类型
    getArticleType().then((response) => {
      this.visitTypeOptions = response.result.data;
    });
  },
  methods: {
    getPageInfo() {
      getPage(this.queryParams).then((response) => {
        this.treeOptions = response.result.data;
        if (response.result.data.length > 0) {
          this.currentId = response.result.data[0].id; //将节点id赋值给上级id
        }
        this.$nextTick(() => {
          //默认当前选中（主要是为了样式）
          this.$refs.tree.setCurrentKey(this.currentId, true, false);
        });
        // this.defaultExpandkeys[0] = this.currentId;
        this.getList();
      });
    },
    handleNodeClick(data) {
      this.currentId = data.id;
      this.getList();
    },
    getList() {
      this.loading = true;
      if (this.currentId === null) {
        this.loading = false;
        this.tableList = [];
      } else {
        this.queryParams.category = this.currentId;
        listData(this.queryParams).then((response) => {
          this.tableList = response.result.rows;
          this.total = response.result.total;
          this.loading = false;
        });
      }
    },
    getSelect() {
      // 资源库类型 1-公共资料库 2-行业资料库 3-企业资料库
      if (this.theType === 1) {
        // 15-公共资源分类 1
        getDict(15, 1).then((response) => {
          this.classOptions = response.result.data;
        });
      } else if (this.theType === 2) {
        // 13-行业资源分类 0  这个接口废弃了 现在用行业资源分类页面接口
        getDict(1, 1).then((response) => {
          // 1-所属行业 1
          this.industryOptions = response.result.data;
          if (this.industryOptions.length > 0) {
            this.industryParams.industryId = response.result.data[0].id;
            this.industryParams.industry = response.result.data[0].label;
          }
          this.getTree();
        });
      } else if (this.theType === 3) {
        // 14-企业资源分类 0
        getDict(14, 0).then((response) => {
          this.classOptions = response.result.data;
        });
      }
    },
    getTree() {
      getClassTree(this.industryParams).then((response) => {
        console.log("response---", response);
        this.classOptions = response.result.industryClassification;
        if (response.result.industryClassification.length > 0) {
          this.currentId = response.result.industryClassification[0].id;
          this.currentTid = response.result.industryClassification[0].tid;
          this.currentNodeVal = response.result.industryClassification[0].label;
        } else {
          this.currentId = null;
        }
        this.$nextTick(() => {
          //默认当前选中（主要是为了样式）
          this.$refs.tree.setCurrentKey(this.currentId, true, false);
        });
        this.getList();
      });
    },
    // 所属行业下拉框 节点单击事件
    changeIndustry(val) {
      this.industryParams.industry = val
        ? this.industryOptions.find((ele) => ele.id === val).label
        : "";
      this.getTree();
    },
    handleQuery() {
      this.queryParams.currentPage = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    handleAdd(val) {
      this.reset();
      this.open = true;
      this.title = "添加";
    },
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      getData(id).then((response) => {
        this.form = response.result;
        // id
        this.form.theid = response.result.id;
        // 栏目分类
        if (this.theType === 1) {
          // 公共资源
          this.form.baseId = response.result.publicClassificationId;
          this.form.classVal = response.result.publicClassification;
        } else if (this.theType === 2) {
          // 行业资源
          this.form.baseId = response.result.industryClassificationId;
          this.form.classVal = response.result.industryClassification;
        } else if (this.theType === 3) {
          // 企业资源
          this.form.baseId = response.result.enterpriseClassificationId;
          this.form.classVal = response.result.enterpriseClassification;
        }
        this.open = true;
        this.title = "修改";
      });
    },
    submitForm() {
      // 资源库类型 1-公共资料库 2-行业资料库 3-企业资料库
      if (this.theType === 1) {
        this.form.publicClassificationId = this.form.baseId;
        this.form.publicClassification = this.form.classVal;
        this.form.thePublic = 1;
      } else if (this.theType === 2) {
        this.form.industryClassificationId = this.form.baseId;
        this.form.industryClassification = this.form.classVal;
      } else if (this.theType === 3) {
        this.form.enterpriseClassificationId = this.form.baseId;
        this.form.enterpriseClassification = this.form.classVal;
        this.form.enterprise = 1;
      }
      //资源类别 1-文章 2-视频 3-音频 4-图片
      this.form.category = 1;
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != undefined) {
            updateData(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addData(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        baseId: undefined,
        baseVal: undefined,
        industryClassificationId: undefined,
        industryClassification: undefined,
        enterpriseClassificationId: undefined,
        enterpriseClassification: undefined,
        publicClassificationId: undefined,
        publicClassification: undefined,
        title: undefined,
        theType: undefined,
        content: undefined,
        theLink: undefined,
        introduction: undefined,
        thumb: undefined,
        category: undefined,
        classHours: undefined,
        credit: undefined,
        thePublic: undefined, //是否公共资源 0-不是 1-是
        enterprise: undefined, //是否企业资源 0-不是 1-是
        publisherId: this.$store.state.userInfo.theid, //发布人id
        publisher: this.$store.state.userInfo.thename, //发布人
        industryId: this.industryParams.industryId,
        industry: this.industryParams.industry,
      };
      this.resetForm("form");
    },
    handleDelete(row) {
      const theId = row.id;
      this.$confirm("是否确认删除?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          // 调接口
          return delData(theId);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    // 归档（是/否）
    handlefileChange(row) {
      let text = row.enable === 1 ? "启用" : "停用";
      this.$confirm('是否确认' + text + '"?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          // 调接口 改变状态值
          return getEnable(row.id, row.enable);
        })
        .then(() => {
          this.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.enable = row.enable === 1 ? 0 : 1;
        });
    },
    /** 导入 */
    handleImport() {
      this.upload.title = "导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      /* importTemplate().then(response => {
          this.download(response.msg);
        }); */
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    /** 导出按钮操作 */
    handleExport() {
      // const queryParams = this.queryParams;
      this.$confirm("是否确认导出?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          // 调接口导出表
          // return exportRole(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
        });
    },
    changeClass(val) {
      if (this.classOptions.length > 0) {
        this.form.classVal = val
          ? this.classOptions.find((ele) => ele.id === val).label
          : "";
      }
    },
    changeType(val) {
      // this.form.classVal = val ? this.classOptions.find(ele => ele.id === val).label : ''
    },
    findVisitType(val) {
      if (this.visitTypeOptions.length > 0) {
        let value = val
          ? this.visitTypeOptions.find((ele) => ele.id === val).label
          : "";
        return value;
      }
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.userId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /* changeVisitType(val) {
        console.log('val',val)
        if (val===2) { //PPT
          this.fileType = ["pptx"];
        }else if (val===3) { //PDF
          this.fileType = ["pdf"];
        }else if (val===4) { //WORD
          this.fileType = ["doc", "docx"];
        }
      } */
  },
};
</script>

<style scoped lang="scss">
/deep/ .el-tooltip__popper {
  max-width: 300px !important;
  font-size: 14px;
}
/* treeselect */
.vue-treeselect__input {
  display: block;
}
/deep/ .vue-treeselect__control {
  height: 32px;
  line-height: 32px;
  margin-top: 3px;
}
/* .el-date-editor*/
/deep/ .el-dialog__body .el-date-editor.el-input,
/deep/ .el-dialog__body .el-date-editor.el-input__inner {
  // width: 220px;
  width: auto !important;
}
/* 去掉动画 */
.component-upload /deep/ .el-upload-list__item {
  transition: none !important;
}
.el-upload__tip {
  display: inline-block;
  margin-left: 14px;
}
</style>

